import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReaderExample {

	public static String readFileCharByChar(String fileName) throws IOException {
		StringBuilder fileContents = new StringBuilder();
		FileReader reader = new FileReader(fileName);
		try {
			int nextChar;
			while ((nextChar = reader.read()) != -1) {
				char nextCh = (char) nextChar;
				fileContents.append(nextCh);
			}
		} finally {
			reader.close();
		}
		String fileContentsStr = fileContents.toString(); 
		return fileContentsStr;
	}

	public static String readFileWithBuffer(String fileName) throws IOException {
		StringBuilder fileContents = new StringBuilder();
		char[] buf = new char[16 * 1024]; // 16 KB buffer
		FileReader reader = new FileReader(fileName);
		try {
			while (true) {
			  int bytesRead = reader.read(buf);
			  if (bytesRead == -1) {
				  // End of stream reached
				  break;
			  }
			  fileContents.append(buf, 0, bytesRead);
			}
		} finally {
			reader.close();
		}
		String fileContentsStr = fileContents.toString(); 
		return fileContentsStr;
	}

	public static String readFileLineByLine(String fileName) throws IOException {
		StringBuilder fileContents = new StringBuilder();
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		try {
			while (true) {
			  String line = reader.readLine();
			  if (line == null) {
				  // End of stream reached
				  break;
			  }
			  fileContents.append(line);
			  fileContents.append("\n");
			}
		} finally {
			reader.close();
		}
		String fileContentsStr = fileContents.toString(); 
		return fileContentsStr;
	}

	public static void main(String[] args) throws IOException {
		System.out.println("---- Reading with read() - char by char ----");
		String fileContents = readFileCharByChar("some-file.txt");
		System.out.println(fileContents);

		System.out.println("---- Reading - read(char[] buf) - with buffering ----");
		fileContents = readFileWithBuffer("some-file.txt");
		System.out.println(fileContents);

		System.out.println("---- Reading with readLine() - line by line ----");
		fileContents = readFileLineByLine("some-file.txt");
		System.out.println(fileContents);
	}
}
